<template>
  <div class="remote-select">
    <el-select
      remote
      filterable
      reserve-keyword
      v-model="value"
      :loading="loading"
      :placeholder="placeholder"
      :remote-method="remoteMethod"
      @change="handleSelectOption"
    >
      <el-option
        v-for="item in options"
        :key="item[optionKeys[1]]"
        :label="item[optionKeys[0]]"
        :value="item[optionKeys[1]]">
      </el-option>
    </el-select>
    <div>
      <el-button
        :type="buttonType"
        :icon="buttonIcon"
        :disabled="disabled"
        @click="handleClick"
      ></el-button>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    disabled: { // 组件禁用状态，默认不禁用
      type: Boolean,
      default: false
    },
    echoValue: { // 选择框已有回显value，默认空串
      type: String,
      default: ''
    },
    echoOptions: { // 选择框已有回显options，默认空
      type: Array,
      default () { return []; }
    },
    optionKeys: {
      type: Array,
      default () { // 第一位传label key，第二位传value key
        return ['label', 'value'];
      }
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    remoteSelectOptions: { // 远程请求下拉options
      type: Function,
      default: () => {}
    },
    buttonType: { // 按钮类型，默认primary
      type: String,
      default: 'primary'
    },
    buttonIcon: { // 按钮图标，默认搜索图标
      type: String,
      default: 'el-icon-search'
    },
    handleClickButton: { // 按钮点击事件
      type: Function,
      default: () => {}
    }
  },
  data () {
    return {
      value: '',
      options: [],
      loading: false
    }
  },
  watch: {
    echoValue: {
      handler(val) {
        this.value = val;
      },
      immediate: true
    },
    echoOptions (val) {
      const hasOptions = val.every(item => item);
      // 下标0对应label，下标1对应value
      if (hasOptions) {
        this.options = [{
          [this.optionKeys[0]]: val[0],
          [this.optionKeys[1]]: val[1],
        }];
      }
    }
  },
  methods: {
    async remoteMethod (queryString) {
      if (!queryString) {
        this.options = [];
        return false;
      }
      this.options = await this.remoteSelectOptions(
        queryString,
        state => { this.loading = state; }
      );
    },
    // 选择option
    handleSelectOption (val) {
      const target = this.options.find(item => item[this.optionKeys[1]] === val);
      this.$emit('getSelect', target ?? {});
    },
    // 按钮点击
    handleClick () {
      this.handleClickButton();
    },
    // 清空当前值
    clearValue () {
      this.value = ''
    },
    // 清空下拉选项
    clearOptions () {
      this.options = []
    }
  }
}
</script>
<style>
.remote-select {
  display: flex;
}
</style>
